package com.seckill.config;

import com.seckill.entity.SeckillUser;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        argumentResolvers.add(handlerMethodArgumentResolver());
    }

    @Bean
    public HandlerMethodArgumentResolver handlerMethodArgumentResolver(){
        return new HandlerMethodArgumentResolver(){

            @Override
            public boolean supportsParameter(MethodParameter methodParameter) {
                Class<?> clazz = methodParameter.getParameterType();
                return clazz == SeckillUser.class;
            }

            @Override
            public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
                System.out.println("开始获取SeckillUser");
                HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
                HttpServletResponse response = nativeWebRequest.getNativeResponse(HttpServletResponse.class);

                SeckillUser user = new SeckillUser();
                user.setId(8888L);
                user.setNickname("百晓生");
                return user;
            }
        };
    }
}
